package by.sjc.grsu.service.impl;

import by.sjc.grsu.dao.repositiory.PeriodicalsDao;
import by.sjc.grsu.model.Account;
import by.sjc.grsu.model.Periodical;
import by.sjc.grsu.service.PeriodicalsService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PeriodicalsServiceImpl implements PeriodicalsService {
    public static final Logger logger = Logger.getLogger(PeriodicalsServiceImpl.class);

    @Autowired
    private PeriodicalsDao periodicalsDao;

    @Override
    public List<Periodical> getAllPeriodicals() {
        return periodicalsDao.findAll();
    }

    @Override
    public boolean addPeriodical(Periodical periodical) {
        if ( !periodicalsDao.isExist(periodical.getName()) ) {
            try {
                periodicalsDao.save(periodical);
                return true;
            } catch (Exception ex) {
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean editPeriodical(Periodical periodical) {
        Periodical existedPeriodical = periodicalsDao.findById(periodical.getId());

        if ( null != existedPeriodical && (
                    existedPeriodical.getName().equals( periodical.getName() ) ||
                    !periodicalsDao.isExist( periodical.getName() )
                )) {
            try {
                logger.info("update "+periodical);
                periodicalsDao.update(periodical);
                return true;
            } catch (Exception ex) {
                return false;
            }
        }
        return false;
    }

    @Override
    public Periodical getById(int id) {
        return periodicalsDao.findById(id);
    }

    @Override
    public void deleteById(int id) {
        periodicalsDao.delete(id);
    }
}
